﻿using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using CloudShot.Utils.Drawings;

namespace DrawTools.Editor.CanvasFigures
{
  public class CanvasCrop : CanvasRectangle
  {
    public CanvasCrop(int x, int y, int width, int height)
      : base(x, y, width, height)
    {
      TrackerColor = Color.IndianRed;
    }

    /// <summary>
    ///   Draw rectangle
    /// </summary>
    /// <param name="graphics"></param>
    public override void Draw(Graphics graphics)
    {
      using (var borderPen = new Pen(Color.Black, 1))
      using (var focusPen = new Pen(Color.White, 1))
      {
        focusPen.DashPattern = new[]
        {
          6.0F,
          4.0F
        };

        Rectangle rect = GetNormalizedRectangle(Rectangle);

        var path = new GraphicsPath();
        // add the desired path
        path.AddRectangle(rect);

        // add the rectangle to invert the inside
        path.AddRectangle(Screen.PrimaryScreen.Bounds);

        using (var brush = new SolidBrush(Color.FromArgb(120, Color.Black)))
        {
          graphics.FillPath(brush, path);
        }

        graphics.DrawRectangle(borderPen, rect);
        graphics.DrawRectangle(focusPen, rect);

        Point point = new Point(rect.Right, rect.Bottom);
        string label = string.Format("{0} x {1}", rect.Width, rect.Height);
        graphics.DrawTextUnderCursor(label, new Point(point.X + 1, point.Y + 1), SystemFonts.DefaultFont, (int)graphics.ClipBounds.Width, (int)graphics.ClipBounds.Height, false);
      }
    }

    /// <summary>
    ///   Hit test.
    ///   Return value: -1 - no hit
    ///   0 - hit anywhere
    ///   > 1 - handle number
    /// </summary>
    /// <param name="point"></param>
    /// <returns></returns>
    public override int HitTest(Point point)
    {
      const int hoverRadius = 5;

      int result = base.HitTest(point);

      if (result > 0)
        return result;

      Rectangle rect = GetNormalizedRectangle(Rectangle);

      if (IsInInterval(point.X, rect.Left - hoverRadius, rect.Left + hoverRadius))
        return 0;

      if (IsInInterval(point.X, rect.Right - hoverRadius, rect.Right + hoverRadius))
        return 0;

      if (IsInInterval(point.Y, rect.Top - hoverRadius, rect.Top + hoverRadius))
        return 0;

      if (IsInInterval(point.Y, rect.Bottom - hoverRadius, rect.Bottom + hoverRadius))
        return 0;

      return -1;
    }

    private static bool IsInInterval(int value, int start, int end)
    {
      return value >= start && value <= end;
    }
  }
}